package com.cqhfan.chatroom.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.cqhfan.chatroom.domain.po.ChatGroup;
import com.cqhfan.chatroom.domain.po.ChatList;
import com.cqhfan.chatroom.domain.po.ChatMessage;
import com.cqhfan.chatroom.domain.po.User;
import com.cqhfan.chatroom.domain.vo.ChatListVO;
import com.cqhfan.chatroom.domain.vo.MyFriendVO;
import com.cqhfan.chatroom.enums.ChatType;
import com.cqhfan.chatroom.mapper.ChatGroupMapper;
import com.cqhfan.chatroom.mapper.ChatListMapper;
import com.cqhfan.chatroom.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqhfan.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户聊天列表项 服务实现类
 * </p>
 *
 * @author 眭传洪
 * @since 2024-11-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatListServiceImpl extends ServiceImpl<ChatListMapper, ChatList> implements IChatListService {

    private final IChatMessageService chatMessageService;

    private final IUserService userService;

    private final IFriendService friendService;

    private final ChatGroupMapper chatGroupMapper;

    @Override
    @Transactional
    public void createChatListItem(ChatList body) {
        Long userId = UserContext.getUser();
        Long receiverId = body.getReceiverId();

        // 单聊需要保存我和你的记录
        // 我的
        ChatList chatList = lambdaQuery()
                .eq(ChatList::getUserId, userId)
                .eq(ChatList::getReceiverId, receiverId)
                .eq(ChatList::getType, ChatType.SINGLE.getValue())
                .one();
        if (chatList == null) {
            body.setUserId(userId);
            save(body);
        }
    }

    @Override
    public List<ChatListVO> listMyChatList() {
        // 分页查询我的聊天列表数据
        Long userId = UserContext.getUser();
        List<ChatList> chatLists = lambdaQuery().eq(ChatList::getUserId, userId).list();
        if (CollUtil.isEmpty(chatLists)) {
            return Collections.emptyList();
        }

        // 获取群聊数据
        List<Long> groupIds = chatLists.stream()
                .filter(item -> item.getType() == ChatType.MULTI)
                .map(ChatList::getGroupId)
                .toList();
        Map<Long, ChatGroup> groupMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(groupIds)) {
            List<ChatGroup> groups = chatGroupMapper.selectBatchIds(groupIds);
            groupMap = groups.stream().collect(Collectors.toMap(ChatGroup::getId, cg -> cg));
        }

        // 根据聊天项的id拿到最后一条消息的id和内容
        List<Long> chatListIds = chatLists.stream().map(ChatList::getId).toList();
        List<ChatMessage> messages = chatMessageService.lambdaQuery()
                .in(ChatMessage::getChatListId, chatListIds)
                .orderByDesc(ChatMessage::getCreateTime)
                .last("limit 1")
                .list();
        Map<Long, ChatMessage> messageMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(messages)) {
            messageMap = messages.stream().collect(Collectors.toMap(ChatMessage::getChatListId, m -> m));
        }

        // 获取用户信息
        List<Long> userIds = messages.stream().map(ChatMessage::getSenderId).toList();
        Map<Long, User> userMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(userIds)) {
            List<User> users = userService.lambdaQuery().in(User::getId, userIds).list();
            userMap = users.stream().collect(Collectors.toMap(User::getId, u -> u));
        }

        // 获取我的朋友信息
        List<MyFriendVO> friends = friendService.listMyFriends();
        Map<Long, MyFriendVO> friendsMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(friends)) {
            friendsMap = friends.stream().collect(Collectors.toMap(MyFriendVO::getId, f -> f));
        }

        // 组装VO
        List<ChatListVO> result = new ArrayList<>(chatLists.size());
        for (ChatList chatList : chatLists) {
            // 聊天列表信息设置
            Long chatListId = chatList.getId();
            ChatListVO vo = new ChatListVO();
            result.add(vo);
            vo.setId(chatListId);
            ChatType type = chatList.getType();
            vo.setType(type.getValue());

            // 设置聊天数据
            Long messageUserId = chatList.getReceiverId();
            User user = userMap.get(messageUserId);
            MyFriendVO friend = friendsMap.get(messageUserId);
            if (type == ChatType.SINGLE) {
                // 单聊需要设置备注和头像
                if (user != null) {
                    vo.setReceiverId(messageUserId);
                    vo.setAvatar(user.getAvatar());
                    vo.setLastMessageNickName(friend.getRemark());
                }
            } else {
                Long groupId = chatList.getGroupId();
                ChatGroup chatGroup = groupMap.get(chatList.getGroupId());
                if (chatGroup != null) {
                    vo.setGroupId(groupId);
                    vo.setGroupName(chatGroup.getGroupName());
                    vo.setAvatar(chatGroup.getGroupAvatar());
                }
                if (user != null) {
                    // 备注信息 如果不是我的朋友 则设置为昵称
                    vo.setLastMessageNickName(friend == null ? user.getNickname() : friend.getRemark());
                }
            }
            vo.setLastMessageTime(chatList.getCreateTime());
            ChatMessage message = messageMap.get(chatListId);
            if (message == null) {
                continue;
            }
            vo.setLastMessageContent(message.getContent());
            vo.setLastMessageTime(message.getCreateTime());
            // TODO
            vo.setUnReaderMessageNums(10);
        }

        // 按照消息时间降序排列
        result.sort(Comparator.comparing(ChatListVO::getLastMessageTime).reversed());
        return result;
    }
}
